package com.webserver_v4.core;

import com.webserver_v4.http.HttpServletRequest;

import java.io.*;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class ClientHandler implements Runnable{
    private Socket socket;
    private static File rootDir;
    private static File staticDir;
    public ClientHandler(Socket socket){
        this.socket = socket;
    }

    static {
        try {
            rootDir = new File(
                    ClientHandler.class.getClassLoader()
                    .getResource(".").toURI()
            );
            staticDir = new File(rootDir,"static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        try {
           //1.解析请求
            HttpServletRequest request = new HttpServletRequest(socket);
            //2.处理请求
            String path = request.getUri();
            File file = new File(staticDir,path);
            int statusCode;
            String statusReason;
            if (file.isFile()){
                statusCode = 200;
                statusReason = "OK";
            }else {
                statusCode = 404;
                statusReason = "NotFound";
                file = new File(staticDir,"root/404.html");
            }
            //3.发送响应

            System.out.println("文件是否存在:"+file.exists());
            //(3.1).发送状态行
            println("HTTP/1.1 200 OK");

            //(3.2).发送响应头
            println("Content-Type: text/html");
            println("Content-Length: "+file.length());

            //(3.3).单独发送回车换行
            println("");

            //(3.3).发送响应正文
            OutputStream out = socket.getOutputStream();
            FileInputStream fis = new FileInputStream(file);
            byte[] data = new byte[10240];
            int len;
            while ((len = fis.read(data))!=-1){
                out.write(data,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    private void println(String line) throws IOException {
        OutputStream out  = socket.getOutputStream();
        out.write(line.getBytes(StandardCharsets.ISO_8859_1));
        out.write(13);
        out.write(10);
    }

}
